package jrunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;


public class ImportPersonObject implements ImportPersonData {

	private ArrayList<Person> personList;
	private FileInputStream fis;
	private ObjectInputStream ois;
	private String directoryName;
	
	//Field values for all new Objects.
	{
		directoryName = "personData";
		personList = new ArrayList<Person>();
	}
	
	public ArrayList<Person> importPersonData() {
		
		//Get all files with the suffix .person
		//Create an ObjectInputStream loading all persons
		//into an ArrayList<Person>.
		File directory = new File(directoryName);
		
		String[] fileList = directory.list(new PersonFilter());
		
		for(String s:fileList){
			File file = new File(directoryName + "/" + s);
			
			try {
				fis = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			try {
				ois = new ObjectInputStream(fis);
				try {
					Person p = (Person) ois.readObject();
					personList.add(p);
					
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
		
		return personList;
		//ToDo: Die Personen Liste alphabetisch nach dem Namen sortieren.
	}
	public static void main(String[] args){
		ImportPersonObject ipo = new ImportPersonObject();
		ArrayList<Person> list = ipo.importPersonData();
		for(Person p:list){
			System.out.println(p.toString());
			System.out.println("Du hast es geschafft!");
		}
	}

}
